package kr.hyunist.androidcomplete01saeildamil.ch19;

import kr.hyunist.androidcomplete01saeildamil.*;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;

public class LooperEx01 extends Activity {
	int mMainValue = 0;
	TextView mMainText;
	TextView mBackText;
	EditText mNumEdit;
	CalcThread mThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loopertest);

		mMainText = (TextView) findViewById(R.id.loopertesttv1);
		mBackText = (TextView) findViewById(R.id.loopertesttv2);
		mNumEdit = (EditText) findViewById(R.id.loopertestet);

		mThread = new CalcThread(mHandler);
		mThread.setDaemon(true);
		mThread.start();
	}

	public void mOnClick(View v) {
		Message msg;

		switch (v.getId()) {
		case R.id.loopertestbtn1:
			mMainValue++;
			mMainText.setText("MainValue : " + mMainValue);
			break;

		case R.id.loopertestbtn2:
			msg = new Message();
			msg.what = 0;
			msg.arg1 = Integer.parseInt(mNumEdit.getText().toString());
			mThread.mBackHandler.sendMessage(msg);
			break;

		case R.id.loopertestbtn3:
			msg = new Message();
			msg.what = 1;
			msg.arg1 = Integer.parseInt(mNumEdit.getText().toString());
			mThread.mBackHandler.sendMessage(msg);
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 0:
				mBackText.setText("SquareResult : " + msg.arg1);
				break;
				
			case 1:
				mBackText.setText("Root Result : " + ((Double)msg.obj).doubleValue());
				break;
			}
		}
	};

}

class CalcThread extends Thread {
	Handler mMainHandler;
	Handler mBackHandler;

	public CalcThread(Handler handler) {
		mMainHandler = handler;
	}

	@Override
	public void run() {
		Looper.prepare();

		mBackHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				Message retmsg = new Message();
				switch (msg.what) {
				case 0:
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					retmsg.what = 0;
					retmsg.arg1 = msg.arg1 * msg.arg1;
					break;

				case 1:
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					retmsg.what = 1;
					retmsg.obj = new Double(Math.sqrt((double)msg.arg1));
					break;
				}
				mMainHandler.sendMessage(retmsg);
			}

		};

		Looper.loop();
	}

}